package lumis.service.wsrp.producer;

import java.util.Set;

import javax.persistence.NoResultException;

import lumis.doui.processaction.ProcessActionHandler;
import lumis.doui.source.TabularSource;
import lumis.doui.source.field.ITabularSourceField;
import lumis.portal.PortalException;
import lumis.portal.PortalObjectNotFoundException;
import lumis.portal.UnexpectedException;
import lumis.portal.manager.ManagerFactory;

import com.sun.portal.wsrp.producer.ProducerException;

/**
 * Process Action Handler responsible for populating the items served by the
 * {@link ProducerImpl#getOfferedPortletNames()} with the values obtained from
 * the interface. The interface must be configured in order to populate the list
 * and, thus, there must be an instance of {@link ProducerImpl} associated with
 * the current service instance.
 * 
 * @version $Revision: 11180 $ $Date: 2009-12-04 18:13:02 -0200 (Fri, 04 Dec 2009) $
 * @since 5.5.0
 */
public class ProducerAddInterfaceInstanceProcessActionHandler extends ProcessActionHandler<TabularSource<ITabularSourceField>>
{
	public void processAction() throws PortalException
	{
		String serviceInterfaceInstanceId = getParameter("serviceInterfaceInstanceId", String.class);
		if (serviceInterfaceInstanceId == null)
			throw new PortalException(localize("STR_ALL_FIELDS_ARE_REQUIRED"));

		// check serviceInterfaceInstanceId
		try
		{
			ManagerFactory.getServiceInterfaceInstanceManager().get(sessionConfig, serviceInterfaceInstanceId, transaction);
		}
		catch (PortalObjectNotFoundException e)
		{
			throw new PortalException(localize("STR_INVALID_INTERFACE_INSTANCE_ID"));
		}

		// get current service instance's producer
		String serviceInstanceId = douiContext.getRequest().getServiceInstanceConfig().getId();
		ProducerImpl producer;
		try
		{
			producer = (ProducerImpl) ManagerFactory.getEntityManager().createNamedQuery(ProducerImpl.NAMED_QUERY_FIND_PRODUCER_BY_NAMESPACE).setParameter("namespace", serviceInstanceId)
					.getSingleResult();
		}
		catch (NoResultException e)
		{
			producer = null;
		}

		if (producer != null)
		{
			// update producer.offerPortletNames
			try
			{
				Set<String> offeredPortletNames = producer.getOfferedPortletNames();
				if (!(offeredPortletNames.contains(serviceInterfaceInstanceId)))
				{
					offeredPortletNames.add(serviceInterfaceInstanceId);
					producer.setOfferedPortletNames(offeredPortletNames);
					ManagerFactory.getEntityManager().persist(producer);
				}
			}
			catch (ProducerException e)
			{
				throw new UnexpectedException(e);
			}
		}
		else
		{
			throw new PortalException(localize("STR_COULDNT_FIND_PRODUCER"));
		}
		addDefaultResponse();
	}
}
